const router = require("express").Router();
const admin = require("./Data");
const { sign } = require("../../../utils/token");
router.post("/login", async (req, res) => {
  try {
    console.log(admin);
    const { username, password } = req.body;
    const resq = await admin.findOne({ username });
    console.log(resq);
    if (!resq) return res.cc(401, '用户不存在')
    if (resq.password == password) {
      res.status(200).json({
        message: "登录成功",
        data: resq,
        token: sign({ username: resq.username }),
      });
    } else {
      res.cc(401, "用户名或密码错误");
    }
  } catch (error) {
    console.error(error);
    res.cc(error);
  }
});

router.post("/register", async (req, res) => {
  try {
    const { username, password } = req.body;
    const resq = await admin.findOne({ username });
    if (resq) return res.cc(401, "用户名已存在");
    const newAdmin = await admin.create({ username, password });
    if (newAdmin) {
      res.status(200).json({
        message: "注册成功",
        data: newAdmin,
      });
    }
  } catch (error) {
    console.log(error);
    res.cc(401, "注册失败");
  }
});
module.exports = router;
